package com.cjd.common.utils

import android.app.Activity
import java.util.*

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2017/6/19.
 * description 业务逻辑 Stack 工具类
 */
object AppManager {

    private val activityStack: Stack<Activity> by lazy {
        Stack<Activity>()
    }

    /**
     * <获取当前栈顶Activity>
     * <功能详细描述>
     *
     * @return Activity
     * @see [类、类.方法、类.成员]
     * </功能详细描述></获取当前栈顶Activity>
     */
    @JvmStatic
    fun currentActivity(): Activity? {
        val activity = activityStack.lastElement()
        LogUtils.v("get current activity:" + activity.javaClass.simpleName)
        return activity
    }

    /**
     * <将Activity入栈>
     * <功能详细描述>
     *
     * @see [类、类.方法、类.成员]
     * </功能详细描述></将Activity入栈>
     */
    @JvmStatic
    fun pushActivity(activity: Activity) {
        LogUtils.v("push stack activity:" + activity.javaClass.simpleName)
        activityStack.add(activity)
    }

    /**
     * <退出栈顶Activity>
     * <功能详细描述>
     *
     * @see [类、类.方法、类.成员]
     *</功能详细描述></退出栈顶Activity>
     */
    @JvmStatic
    fun popActivity(activity: Activity?) {
        if (activity != null) {
            activity.finish()
            LogUtils.v("remove current activity:" + activity.javaClass.simpleName)
            activityStack.remove(activity)
        }
    }

    /**
     * 结束指定类名的Activity
     */
    @JvmStatic
    fun popActivity(cls: Class<*>) {
        for (activity in activityStack) {
            if (activity.javaClass == cls) {
                popActivity(activity)
                break
            }
        }
    }

    /**
     * <退出栈中所有Activity></退出栈中所有Activity>,当前的activity除外>
     * <功能详细描述>
     *
     * @param cls 类
     * @see [类、类.方法、类.成员]
    </功能详细描述> */
    @JvmStatic
    fun popAllActivityExceptMain(cls: Class<*>) {
        if (activityStack.size == 0)
            return
        for (activity in ArrayList(activityStack)) {
            if (activity.javaClass != cls) {
                popActivity(activity)
            }
        }
    }

}